import { formatDate } from '../electron-kit-extension/tool.js';
class HidManager {
    constructor({ vendorId = 0xA8A4, productId = 0x2255, interfaceId = 0 } = {}) {
        this.vendorId = vendorId;
        this.productId = productId;
        this.interfaceId = interfaceId;
        this.hidDevice = null;
    }

    ///获取设备列表，并且连接指定设备
    async getHidDevices() {
        try {
            const devices = await navigator.hid.getDevices();
            if (devices.length === 0) {
                return null;
            }
            console.log(devices);
            devices.forEach(e => this.connectHid(e));
            return devices;
        } catch (error) {
            console.error('Error Auto requesting HID device:', error);
        }
    }

    ///请求授权的设备
    async requestHidDevices() {
        try {
            const devices = await navigator.hid.requestDevice({
                filters: [{ vendorId: vendorId, productId: productId }]
            })

            if (devices.length === 0) {
                console.warn('未选择设备')
                return null
            }
            // 之后可以使用device进行通信
            return devices
        } catch (error) {
            console.error('请求设备失败::', error)
        }
    }

    /// 监听 HID 插拔信息
    listenerHidDeviceState() {
        navigator.hid.addEventListener('connect', (event) => {
            const device = event.device;
            console.log("=============>✅ 检测到插入的设备:", device.vendorId, device);
            this.connectHid(device); // 此处直接传入 device
        });

        navigator.hid.addEventListener('disconnect', (event) => {
            const device = event.device;
            console.log('=============> ❌ 检测到拔掉设备:', device.vendorId, device);
            this.disConnectHid(device);
        });
    }

    /// 发送 HID 数据
    async sendHidData(data, reportId = 0) {
        try {
            const bytes = data.map(v => v.toString(16).toUpperCase().padStart(2, '0')).join(' |');
            if (!this.hidDevice || !this.hidDevice.opened) {
                console.error(formatDate() + ' ----' + '❌❌❌❌❌❌ ' + this.vendorId + ' : HID未连接: ' + bytes);
                return;
            }
            const dataToSend = new Uint8Array(data);
            await this.hidDevice.sendReport(reportId, dataToSend);
            console.log(formatDate() + '----' + '📤📤 已发送数据:' + bytes);
        } catch (error) {
            console.error('发送 HID 数据失败:', error);
        }
    }

    // 连接指定设备
    async connectHid(device) {
        try {
            console.log('尝试连接设备:');
            if (
                device.vendorId === this.vendorId &&
                device.productId === this.productId &&
                device.collections?.length > 0 &&
                device.collections[0].usage === this.interfaceId
            ) {
                this.hidDevice = device;

                if (this.hidDevice.opened) {
                    await this.hidDevice.close();
                }

                await this.hidDevice.open();
                console.log('============> 😄 连接成功');
                this.notifyHidStatusChange(true, this.hidDevice);

                this.hidDevice.addEventListener('inputreport', (event) => {
                    const { data, reportId } = event;
                    const receivedData = new Uint8Array(data.buffer);
                    const bytesString = Array.from(receivedData).map(n => n.toString(16).padStart(2, '0').toUpperCase()).join(', ');
                    console.log('接收数据:', bytesString);
                    this.notifyHidReceiveData(receivedData, reportId);
                });
            } else {
                console.log('设备不符合预期条件，未连接');
            }
        } catch (error) {
            console.error('连接设备出错:', error);
        }
    }

    /// 断开 HID 设备
    async disConnectHid(device) {
        try {
            if (!this.hidDevice) {
                console.log('无设备连接，无需断开');
                return;
            }
            console.log('尝试断开设备:');
            if (
                device.vendorId === this.vendorId &&
                device.productId === this.productId &&
                device.collections?.length > 0 &&
                device.collections[0].usage === this.interfaceId
            ) {
                if (this.hidDevice.opened) {
                    await this.hidDevice.close();
                }
                console.log('============> 🔌🔌 已断开连接');
                this.hidDevice = null;
                this.notifyHidStatusChange(false, null);
            } else {
                console.log('拔出的设备与当前连接的设备不匹配，无需断开');
            }
        } catch (error) {
            console.error('断开设备出错:', error);
        }
    }


    /// 通知页面状态更新（连接/断开时调用）
    notifyHidStatusChange(connected, device = null) {
        const event = new CustomEvent('hid-status-change', {
            detail: {
                connected,         // 'connected' | 'disconnected'
                device          // 可选，传递当前设备
            }
        });
        window.dispatchEvent(event);
    }

    /// 通知接收数据
    notifyHidReceiveData(data, reportId) {
        const event = new CustomEvent('hid-receive-data', {
            detail: {
                data,
                reportId
            }
        });
        window.dispatchEvent(event);
    }
}

export default HidManager;
